package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.ProductsPojo;
import com.lei.springbootpractice.pojo.ReviewPojo;
import com.lei.springbootpractice.service.ProductsService;
import com.lei.springbootpractice.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/products")
public class ProductsController {
    @Autowired
    ProductsService productsService;

    @Autowired
    ReviewService reviewService;

    @GetMapping
    public List<ProductsPojo> getAllProducts() {
        return productsService.getAllProducts();
    }

    @GetMapping("/{productId}")
    public ProductsPojo getProductDetail(@PathVariable String productId) {
        return productsService.getProductById(productId);
    }

    @GetMapping("/{productId}/reviews")
    public Map<String, Object> getProductReviews(@PathVariable String productId) {
        Map<String, Object> result = new HashMap<>();
        List<ReviewPojo> reviews = reviewService.getReviewsByProductId(productId);

        // 计算平均评分
        double avgRating = reviews.stream()
                .mapToInt(ReviewPojo::getRate)
                .average()
                .orElse(0.0);

        result.put("reviews", reviews);
        result.put("averageRating", Math.round(avgRating * 10) / 10.0);
        result.put("totalReviews", reviews.size());

        return result;
    }
}
